<template>
	<picker @change="bindPickerChange" @cancel="bindPickerCancel" :value="pickerIndex" :range="range" :mode="mode"
		:range-key="rangeKey" @columnchange="pickerColumnChange" style="width: 100%;">
		<view class="u-flex" v-if="showInput">
			<view class="g-input-picker-wrapper u-flex-1">
				<u-input v-model="labelValue" placeholder="请选择" type="select" input-align="right"/>
				<view style="position: absolute; top: 0;bottom: 0;left: 0;right: 0;z-index: 9;"></view>
			</view>
			<template v-if="clearable && labelValue">
				<view class="u-p-l-10" @tap.stop="bindClear">
					<u-icon name="close-circle" size="28" color="#999999"></u-icon>
				</view>
			</template>
		</view>
		<slot></slot>
	</picker>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		watch,
		onMounted
	} from 'vue'
	const props = defineProps({
		modelValue: {
			type: [String, Number],
			default: '',
		},
		range: {
			type: Array,
			default: [],
		},
		mode: {
			type: String,
			default: 'selector',
		},
		rangeKey: {
			type: String,
			default: 'label',
		},
		showInput: {
			type: Boolean,
			default: true,
		},
		clearable: {
			type: Boolean,
			default: false,
		}
	})
	const labelValue = ref('');
	const pickerIndex = ref(0);
	onMounted(() => {
		// console.log('onMounted',props.mode);
		setLabelValue();
		
	})
	const setLabelValue=()=>{
		if (props.mode == 'date') {
			labelValue.value = props.modelValue
		}
		if (props.mode == 'selector') {
			try {
				let _index = props.range.findIndex(v => v.value == props.modelValue)
				if(_index == -1){
					pickerIndex.value = 0
				}else{
					pickerIndex.value = _index
				}
				labelValue.value = props.range[_index][props.rangeKey];
			} catch (e) {
				
			}
		}
	}
	watch(
		() => props.modelValue,
		newValue => {
			setLabelValue();
		}
	);

	const emit = defineEmits(['update:modelValue']);
	const bindPickerChange = (event) => {
		if (props.mode == 'selector') {
			let index = event.detail.value;
			pickerIndex.value = index;
			let modelValue = props.range[index].value;
			emit('update:modelValue', modelValue);
		}

		if (props.mode == 'date') {
			let modelValue = event.detail.value;
			emit('update:modelValue', modelValue);
		}
	}
	const bindClear = () =>{
		emit('update:modelValue', '');
		pickerIndex.value = 0;
		labelValue.value = ''
	}
	const bindPickerCancel = () => {

	}
	const pickerColumnChange = () => {

	}
</script>

<style lang="scss" scoped>
	.g-input-picker-wrapper {
		position: relative;
		width: 100%;
	}
</style>